package com.dfbz.netctoss.realm;

import com.dfbz.netctoss.entity.AdminInfo;
import com.dfbz.netctoss.entity.Privilege;
import com.dfbz.netctoss.entity.Role;
import com.dfbz.netctoss.service.AdminInfoService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 自定义realm
 */
public class CustomerRealm extends AuthorizingRealm {
    @Autowired
    AdminInfoService service;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //获取身份信息
        String primaryPrincipal =(String) principalCollection.getPrimaryPrincipal();
        AdminInfo admin = service.findRolesByAdminCode(primaryPrincipal);
        if(!CollectionUtils.isEmpty(admin.getRoles())){
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            for (Role role : admin.getRoles()) {
                //添加角色信息
                simpleAuthorizationInfo.addRole(role.getRoleName());
                //添加权限信息
                List<Privilege> privileges = service.selectAllPrivilegeByRId(role.getRoleId());
                if(!CollectionUtils.isEmpty(privileges)){
                    for (Privilege privilege : privileges) {
                        simpleAuthorizationInfo.addStringPermission(privilege.getPrivateUrl());
                    }
                }
            }
            System.out.println(simpleAuthorizationInfo.getRoles().toString());
            return simpleAuthorizationInfo;

        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String)token.getPrincipal();//获得用户名
        AdminInfo adminInfo = service.findByAdmincode(principal);
        if(adminInfo != null){
            return new SimpleAuthenticationInfo(principal, adminInfo.getAdminPassword(),
                    ByteSource.Util.bytes(adminInfo.getAdminCode()) ,this.getName());
        }else {
            return null;
        }

    }


}
